package com.lutzyt.delivery.bean.vo;

import com.lutzyt.delivery.bean.Menu;
import com.lutzyt.delivery.bean.enums.MenuType;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class MenuTree extends Menu {
  @Setter
  @Getter
  private List<MenuTree> children;

  public static List<MenuTree> newTreeList(List<Menu> menuList) {
    List<MenuTree> menuTreeList = new ArrayList<>();
    menuList.forEach(menu -> {
      if (menu.getParent() == null){
        MenuTree menuTree = new MenuTree();
        BeanUtils.copyProperties(menu, menuTree);
        if (menuTree.getType().equals(MenuType.DIRECTORY)){
          // 获取该目录的子菜单
          menuTree.setChildren(getChildrenMenu(menu.getId(), menuList));
        }
        menuTreeList.add(menuTree);
      }
    });
    return menuTreeList;
  }

  /**
   * 获取所有子菜单
   * @param id
   * @param menuList
   * @return
   */
  public static List<MenuTree> getChildrenMenu(Integer id, List<Menu> menuList){
    List<MenuTree> menuTreeList = new ArrayList<>();
    menuList.forEach(menu -> {
      if (id.equals(menu.getParent())){
        MenuTree menuTree = new MenuTree();
        BeanUtils.copyProperties(menu, menuTree);
        if (menuTree.getType().equals(MenuType.DIRECTORY)){
          // 获取该目录的子菜单
          menuTree.setChildren(getChildrenMenu(menu.getId(), menuList));
        }
        menuTreeList.add(menuTree);
      }
    });
    return menuTreeList;
  }

}
